namespace smoothdev.K2.Blackpearl.ClientTools.Wrappers
{
	using System;
	using SourceCode.Workflow.Client;

	internal class 
		UserImpersonationClientConnectionScope
		: IDisposable
	{

		private Connection clientConnection;
		private string backupIdentifier;
		
		public UserImpersonationClientConnectionScope(Connection clientConnection, string userIdentifier)
		{
			if (clientConnection != null && clientConnection.User != null && !String.IsNullOrEmpty(clientConnection.User.Name))
			{
				this.clientConnection = clientConnection;
				this.backupIdentifier = clientConnection.User.Name;
				clientConnection.ImpersonateUser(userIdentifier);
			}
		}

		public void Dispose()
		{
			if (!String.IsNullOrEmpty(backupIdentifier))
				clientConnection.ImpersonateUser(backupIdentifier);
		}

	}
}